function formatTime(time) {
  if (typeof time !== 'number' || time < 0) {
    return time
  }
  const hour = parseInt(time / 3600, 10)
  time %= 3600
  const minute = parseInt(time / 60, 10)
  time = parseInt(time % 60, 10)
  const second = time

  return ([hour, minute, second]).map(function (n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  }).join(':')
}

function formatLocation(longitude, latitude) {
  if (typeof longitude === 'string' && typeof latitude === 'string') {
    longitude = parseFloat(longitude)
    latitude = parseFloat(latitude)
  }
  longitude = longitude.toFixed(2)
  latitude = latitude.toFixed(2)
  return {
    longitude: longitude.toString().split('.'),
    latitude: latitude.toString().split('.')
  }
}

function fib(n) {
  if (n < 1) return 0
  if (n <= 2) return 1
  return fib(n - 1) + fib(n - 2)
}

function formatLeadingZeroNumber(n, digitNum = 2) {
  n = n.toString()
  const needNum = Math.max(digitNum - n.length, 0)
  return new Array(needNum).fill(0).join('') + n
}

//输出格式为：2019-10-30 14:25:55
function formatDateTime(date, withMs = false) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  const ms = date.getMilliseconds()

  let ret = [year, month, day].map(value => formatLeadingZeroNumber(value, 2)).join('-') +
      ' ' + [hour, minute, second].map(value => formatLeadingZeroNumber(value, 2)).join(':')
  if (withMs) {
    ret += '.' + formatLeadingZeroNumber(ms, 3)
  }
  return ret
}

function rTime(date) {
  let json_date = new Date(date).toJSON();
  return new Date(new Date(json_date) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
}

function rTimeStamp(date) {
  let timeStr = rTime(date)
  return convertStrToTime(timeStr)
}

function convertStrToTime(date) {
  date = date.replace(/-/g, '/'); //必须把日期'-'转为'/'
  let timestamp = new Date(date).getTime();
  return timestamp
}

//输出当前时间的字符串，格式为：2020年9月8日 14点13分
function getNowFormatDate() {
  let date = new Date()
  let month = date.getMonth() + 1 < 10 ? (date.getMonth() + 1) : date.getMonth() + 1; //获取月,如果小于10,前面补个0
  let strDate = date.getDate() < 10 ? date.getDate() : date.getDate(); //获取日,如果小于10,前面补个0
  let strHours = date.getHours() < 10 ? date.getHours() : date.getHours(); //获取小时,如果小于10,前面补个0
  let strMinutes = date.getMinutes() < 10 ? date.getMinutes() : date.getMinutes(); //获取分,如果小于10,前面补个0
  let strSeconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); //获取秒,如果小于10,前面补个0
  let currentdate = date.getFullYear() + "年" + month + "月" + strDate + "日" + strHours + "点" + strMinutes + "分"; //拼接一下
  return currentdate;
}

//输出当前时间的字符串，格式为：12/12 12:12
function getDateTime(date = new Date()) {
  var date_time = formatDateTime(date);
  date_time = date_time.slice(date_time.indexOf("-") + 1, date_time.lastIndexOf(":")).replace("-", "/")
  return date_time
}

function getStampBySpan(start, span) {
  let dateStart = new Date(start.replace(/-/g, "/")).getTime()
  let dateValue = dateStart + span * 60 * 1000
  return dateValue
}

function getTimeSpan(start, end) {
  if (!end) return 0
  let dateStart = new Date(start.replace(/-/g, "/"));
  let dateEnd = new Date(end.replace(/-/g, "/"));
  let dateDiff = dateEnd.getTime() - dateStart.getTime();//时间差的毫秒数
  let minuteDiff = dateDiff / 1000 / 60
  return minuteDiff
}

function getClientInfo() {
  const fpPromise = new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.onload = resolve
    script.onerror = reject
    script.async = true
    // script.src = 'https://openfpcdn.io/fingerprintjs/v3'
    // script.src = 'https://oss-emcsprod-public.modb.pro/static/fingerprint2.min.js'
    script.src = 'https://cdn.jsdelivr.net/npm/@fingerprintjs/fingerprintjs@3/dist/fp.min.js'
    document.head.appendChild(script)
  }).then(() => FingerprintJS.load())

  // Get the visitor identifier when you need it.
  fpPromise
      .then(fp => fp.get())
      .then(result => {
        // This is the visitor identifier:
        const visitorId = result.visitorId
        console.log("visitorId===", visitorId)
      })
}

function getExplore() {
  var Sys = {};
  var ua = navigator.userAgent.toLowerCase();
  var s;
  (s = ua.match(/rv:([\d.]+)\) like gecko/)) ? Sys.ie = s[1] :
      (s = ua.match(/msie ([\d\.]+)/)) ? Sys.ie = s[1] :
          (s = ua.match(/edge\/([\d\.]+)/)) ? Sys.edge = s[1] :
              (s = ua.match(/firefox\/([\d\.]+)/)) ? Sys.firefox = s[1] :
                  (s = ua.match(/(?:opera|opr).([\d\.]+)/)) ? Sys.opera = s[1] :
                      (s = ua.match(/chrome\/([\d\.]+)/)) ? Sys.chrome = s[1] :
                          (s = ua.match(/version\/([\d\.]+).*safari/)) ? Sys.safari = s[1] : 0;
  // 根据关系进行判断
  if (Sys.ie) return ('IE: ' + Sys.ie);
  if (Sys.edge) return ('EDGE: ' + Sys.edge);
  if (Sys.firefox) return ('Firefox: ' + Sys.firefox);
  if (Sys.chrome) return ('Chrome: ' + Sys.chrome);
  if (Sys.opera) return ('Opera: ' + Sys.opera);
  if (Sys.safari) return ('Safari: ' + Sys.safari);
  return 'Unkonwn';
}

function loadJS(url, callback) {
  var script = document.createElement('script'), fn = callback || function () {
  }
  script.type = 'text/javascript';
  //IE
  if (script.readyState) {
    script.onreadystatechange = function () {
      if (script.readyState == 'loaded' || script.readyState == 'complete') {
        script.onreadystatechange = null;
        fn();
      }
    };
  } else {
    //其他浏览器
    script.onload = function () {
      fn();
    };
  }
  script.src = url;
  document.getElementsByTagName('head')[0].appendChild(script);
}

module.exports = {
  formatTime,
  formatLocation,
  fib,
  rTime,
  rTimeStamp,
  convertStrToTime,
  formatDateTime,
  getDateTime,
  getNowFormatDate,
  getStampBySpan,
  getTimeSpan,
  getClientInfo,
  getExplore,
  loadJS
}
